package ru.smc.hogwarts.servlets.professors;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Person;
import ru.smc.hogwarts.model.Subject;

public class ProfessorsInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpSession session;
       
    public ProfessorsInfo() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
    	session.setAttribute("servletName", getServletName());
		
    	long id = 0;
		
		try {
			id = Long.parseLong(request.getParameter("id"));
		} catch (NumberFormatException e) {}
		
		EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
		
		Person professor = em.find(Person.class, id);
		
		if (professor == null) {
			request.getRequestDispatcher("/pages/error/error.jsp").forward(request, response);
		} else {
			request.setAttribute("professor", professor);
			
			Subject subject = (Subject)em.createQuery("select s from Subject s where s.professor.id = " + id).getSingleResult();
			request.setAttribute("subject", subject);
				
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/pages/professors/professorInfo.jsp");
			dispatcher.forward(request, response);
		}
		
		em.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
